package great.easychat.help.uinque;

import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 关键管理
 * 这里文件管理比较简单只处理了文件创建以及文件列表获取
 */
public class FileUtil {
    private static FileUtil fileUtil;
    private final static String TAG = "FileUtil";

    private FileUtil() {

    }

    public static synchronized FileUtil getInstance() {
        if (fileUtil == null) {
            fileUtil = new FileUtil();
        }
        return fileUtil;
    }

    //获取sdcard目录
    public static String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);// 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
        }
        return sdDir.toString();
    }

    //创建目录，不限目录层级
    public static String mkdirs(String path) {
        String sdcard = getSDPath();
        if (!path.contains(getSDPath())) {
            path = sdcard + (path.indexOf("/") == 0 ? "" : "/") + path;
        }
        File destDir = new File(path);
        if (!destDir.exists()) {
            path = makedir(path);
        }
        Log.d("error", "fileName ===》" + path);
        return path;
    }

    private static String makedir(String path) {
        String sdPath = getSDPath();
        String[] dirs = path.replace(sdPath, "").split("/");
        StringBuilder filePath = new StringBuilder(sdPath);
        for (String dir : dirs) {
            if (!"".equals(dir) && !dir.equals(sdPath)) {
                filePath.append("/").append(dir);
                File destDir = new File(filePath.toString());
                if (!destDir.exists()) {
                    boolean b = destDir.mkdirs();
                    if (!b) {
                        return null;
                    }
                }
            }
        }
        return filePath.toString();
    }


    public List<String> getFilesAllName(String path) {
        String sdcard = getSDPath();
        if (!path.contains(getSDPath())) {
            path = sdcard + (path.indexOf("/") == 0 ? "" : "/") + path;
        }
        File file = new File(path);
        File[] files = file.listFiles();
        if (files == null) {
            Log.e(TAG, "空目录 检查文件读写权限是否已经给予 WRITE_EXTERNAL_STORAGE");
            return null;
        }
        List<String> s = new ArrayList<>();
        for (File value : files) {
            s.add(value.getName());
        }
        Log.d(TAG, "fileName ===》" + s);
        return s;
    }

    public String getFilesName(String path) {
        List<String> files = getFilesAllName(path);
        String s = null;
        if (files != null && files.size() > 0) {
            s = files.get(files.size() - 1);
        }
        return s;
    }
}
